#include "ThreadPool.h"



ThreadPool::ThreadPool(size_t threadNum,size_t queSize)
:m_threadNum(threadNum)
,m_queSize(queSize)
,m_que(queSize)
,m_isExit(false)
{}

ThreadPool::~ThreadPool(){}

void ThreadPool::start(){
    for(size_t idx = 0 ; idx < m_threadNum ; ++idx){
        m_threads.push_back(thread(&ThreadPool::doTask,this));
    }
}

void ThreadPool::stop(){
    while(!m_que.empty()){
        sleep(1);
    }
    m_isExit = true;
    m_que.wakeup();

    for(auto &th:m_threads){
        th.join();
    }
}
void ThreadPool::addTask(ElemType &&ptask){
    if(ptask){
        m_que.push(std::move(ptask));
    }
}


ElemType ThreadPool::getTask(){
    return m_que.pop();
}

void ThreadPool::doTask(){
    while(!m_isExit){
        cout<<"i am worker,i am going to work"<<endl;
        ElemType ptask = getTask();
        //一开始阻塞在这里，线程进入条件队列
        if(ptask){
            ptask();
            //执行process
        }else{
            cout<<"ptask == nullptr"<<endl;
        }
    }
}
